package com.foreveross.common.filter;

import java.io.IOException;

import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wm
 * 
 */
public class ParamFilter implements Filter {
	private static final String SHOW_LOGIN_PATH = "SHOW_LOGIN_PATH"; // 显示登录页面
	private static final String DO_LOGIN_PATH = "DO_LOGIN_PATH"; // 登录操作不能过滤掉
	private String showloginPath;
	private String dologinPath;
	//非法字符集
	private String inj_str = "'|and|exec|insert|select|delete|update|count|*|like"
			+ "|chr|mid|master|truncate|char|declare|;|or|\"|=|"
			+ "script|<|&|>|iframe|http|post|function|alert|prompt|"
			+ "session|cookie|document|escape|unescape|src|link|"
			+ "onclick|onmouse|onload|onselect|onkey|onsubmit|onselect|onresize|onreset|ondblclick|onerror|"
			+ "onabort|onblur|onchange|onfocus|onunload";
	
	protected boolean ignore = true;
	protected FilterConfig filterConfig = null;

	public void init(FilterConfig config) throws ServletException {
		showloginPath = config.getInitParameter(SHOW_LOGIN_PATH);
		dologinPath = config.getInitParameter(DO_LOGIN_PATH);
		this.filterConfig = config;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
         HttpServletRequest  httpReq  = (HttpServletRequest) request;  
         HttpServletResponse httpResp = (HttpServletResponse) response;  
         httpResp.setContentType("text/html");  
         String path = httpReq.getContextPath();
     	
         //获取所有的表单参数
         Iterator values = httpReq.getParameterMap().values().iterator();
         while(values.hasNext()){  
        	  String[] value = (String[])values.next();  
        	  for(int i = 0;i < value.length;i++){  
        		  //System.out.println("-------------------------------------- "+value[i]+"       "+sql_inj(value[i]));
	        	  if(sql_inj(value[i])){  
	        		  //System.out.println(">>>>>>>>>>>>>>>> "+path+showloginPath);
	        		  httpResp.sendRedirect(path+showloginPath);
	        		  //httpReq.getRequestDispatcher(showloginPath).forward(httpReq,httpResp);
	        		  return;
	        	  }  
        	  }
         }
         
         chain.doFilter(request, response);  
    }	
         
    public void destroy() {
		// do something
	}

	public boolean sql_inj(String str) {
		String[] inj_stra = inj_str.split("\\|");
		if (str.length() > 200) return true;
		for (int i = 0; i < inj_stra.length; i++) {
			if (str.toLowerCase().indexOf(inj_stra[i]) >= 0) {
				return true;
			}
		}
		return false;
	}

}
